package com.springdatecrm.web.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 *  Shiro配置类
 */

@Configuration
public class ShiroConfig {

    /**
     *  创建 ShiroFillterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {

        System.out.println("ShiroConfiguration.shiroFilter():配置权限控制规则");

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //如果不设置默认会自动寻找 Web 工程目录下的 "/login.jsp" 页面
        shiroFilterFactoryBean.setLoginUrl("/login");

        //登录成功后要跳转的连接
        shiroFilterFactoryBean.setSuccessUrl("/main");

        //未授权界面
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        //添加 shiro 内置过滤器，实现权限相关的 url 拦截
        /**
         *  常见过滤器：
         *  anon:无需认证(登录)可以访问
         *  authc:必须认证才可以访问
         *  user:如果使用 Remeber Me 的功能，可以直接访问
         *  perms:该资源必须得到资源权限才可以访问
         *  role:该资源必须得到角色权限才可以访问
         */
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //配置不会被拦截的连接 顺序判断
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/images/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/localss/**","anon");
        filterChainDefinitionMap.put("/dologin","anon");

        //配置退出 过滤器，其中的具体的退出代码 Shiro 已经替我们实现了
        filterChainDefinitionMap.put("/logout","logout");

        //配置测试权限（真实权限应该从数据库中获得）
        filterChainDefinitionMap.put("/user/list","perms[用户管理]");
        filterChainDefinitionMap.put("/user/add","perms[用户添加]");
        filterChainDefinitionMap.put("/role/list","perms[角色管理]");

        filterChainDefinitionMap.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }


    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        return myShiroRealm;
    }


    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //设置realm
        securityManager.setRealm(myShiroRealm());

        return securityManager;
    }

    /**
     *  配置 thymeleaf 页面对 shiro 标签的支持
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

}
